aregmi.net
Resume

Python Cheat Sheet

String Methods

s.isalpha()        # True if all chars are letters → "abc".isalpha() → True, "ab1".isalpha() → False
s.isdigit()        # True if all chars are digits → "123".isdigit() → True
s.isalnum()        # True if all chars are letters or digits → "abc1".isalnum() → True
s.lower()          # Lowercase copy → "Hello".lower() → "hello"
s.upper()          # Uppercase copy → "hello".upper() → "HELLO"
s.swapcase()       # Swap case → "Hello".swapcase() → "hELLO"
s.capitalize()     # First char upper, rest lower → "hello world".capitalize() → "Hello world"
s.title()          # Title case → "hello world".title() → "Hello World"

s.strip()          # Remove leading/trailing whitespace → "  hi  ".strip() → "hi"
s.lstrip()         # Remove leading whitespace → "  hi  ".lstrip() → "hi  "
s.rstrip()         # Remove trailing whitespace → "  hi  ".rstrip() → "  hi"
s.strip("xy")      # Remove specific chars → "xyhelloxy".strip("xy") → "hello"

s.split()          # Split by whitespace → "a b c".split() → ['a', 'b', 'c']
s.split(",")       # Split by delimiter → "a,b,c".split(",") → ['a', 'b', 'c']
s.split(",", 1)    # Split with max splits → "a,b,c".split(",", 1) → ['a', 'b,c']
s.rsplit(",", 1)   # Split from right → "a,b,c".rsplit(",", 1) → ['a,b', 'c']
s.splitlines()     # Split by newlines → "a\nb\nc".splitlines() → ['a', 'b', 'c']

s.replace(old, new)       # Replace all → "aabaa".replace("a", "x") → "xxbxx"
s.replace(old, new, n)    # Replace first n → "aabaa".replace("a", "x", 2) → "xxbaa"

s.startswith("he")   # Check prefix → "hello".startswith("he") → True
s.endswith("lo")     # Check suffix → "hello".endswith("lo") → True
s.find("ll")         # Index of first match, -1 if not found → "hello".find("ll") → 2
s.rfind("l")         # Index of last match → "hello".rfind("l") → 3
s.index("ll")        # Like find() but raises ValueError if not found
s.count("l")         # Count occurrences → "hello".count("l") → 2
s.count("l", 0, 3)   # Count in slice [0:3] → "hello".count("l", 0, 3) → 1

"".join(list)         # Join list into string → ",".join(["a","b","c"]) → "a,b,c"
s.zfill(5)            # Pad with zeros → "42".zfill(5) → "00042"
s.ljust(10, "-")      # Left-justify → "hi".ljust(10, "-") → "hi--------"
s.rjust(10, "-")      # Right-justify → "hi".rjust(10, "-") → "--------hi"
s.center(10, "-")     # Center → "hi".center(10, "-") → "----hi----"

Character Conversions

chr(97)       # Int → char → 'a'
ord('a')      # Char → int → 97
ord('A')      # → 65
ord('0')      # → 48

# Alphabet tricks
chr(ord('a') + 2)                        # → 'c'
string.ascii_lowercase                   # 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase                   # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits                            # '0123456789'

String Tricks

s[::-1]                    # Reverse → "hello"[::-1] → "olleh"
s[1:4]                     # Slice → "hello"[1:4] → "ell"
s * 3                      # Repeat → "ab" * 3 → "ababab"
"ab" in "abc"              # Substring check → True
f"{var:.2f}"               # Format float → f"{3.14159:.2f}" → "3.14"
f"{var:05d}"               # Zero-pad int → f"{42:05d}" → "00042"
list(s)                    # String to char list → list("abc") → ['a', 'b', 'c']

Collections Module

Counter — Count element frequencies

from collections import Counter

Counter("abracadabra")           # Counter({'a':5, 'b':2, 'r':2, 'c':1, 'd':1})
Counter([1,1,2,3,3,3])          # Counter({3:3, 1:2, 2:1})

c = Counter("hello")
c.most_common(2)                # [('l', 2), ('h', 1)]  — top 2 most frequent
c['l']                          # 2  — access count
c['z']                          # 0  — missing keys return 0 (no KeyError)
c.update("world")               # Add counts from another iterable
list(c.elements())              # Expand back: ['h','e','l','l','o','w','o','r','l','d']

# Counter arithmetic
Counter("aab") + Counter("bcc")   # Counter({'b':2, 'a':2, 'c':2})
Counter("aab") - Counter("ab")    # Counter({'a':1})  — only positive counts kept
Counter("aab") & Counter("abc")   # Counter({'a':1, 'b':1})  — min of each
Counter("aab") | Counter("abc")   # Counter({'a':2, 'b':1, 'c':1})  — max of each

defaultdict — Dict with default values for missing keys

from collections import defaultdict

dd = defaultdict(list)
dd["fruits"].append("apple")     # No KeyError — auto-creates empty list
dd["fruits"].append("banana")
# dd → {'fruits': ['apple', 'banana']}

dd = defaultdict(int)
dd["count"] += 1                 # Auto-creates 0, then adds 1
# dd → {'count': 1}

dd = defaultdict(set)
dd["group"].add("a")             # Auto-creates empty set

deque — Double-ended queue (O(1) append/pop both ends)

from collections import deque

dq = deque([1, 2, 3])
dq.append(4)          # Right end → deque([1, 2, 3, 4])
dq.appendleft(0)      # Left end → deque([0, 1, 2, 3, 4])
dq.pop()              # Remove right → 4
dq.popleft()           # Remove left → 0  (O(1) vs list.pop(0) which is O(n))
dq.rotate(1)           # Rotate right → deque([3, 1, 2])
dq.rotate(-1)          # Rotate left → deque([1, 2, 3])

# BFS pattern
q = deque([(start, 0)])   # (node, depth)
while q:
    node, depth = q.popleft()
    for neighbor in graph[node]:
        q.append((neighbor, depth + 1))

OrderedDict — Dict that remembers insertion order

from collections import OrderedDict

od = OrderedDict()
od['a'] = 1
od['b'] = 2
od.move_to_end('a')           # Move 'a' to end → OrderedDict([('b',2), ('a',1)])
od.move_to_end('a', last=False)  # Move to front
od.popitem(last=True)          # Remove last item
od.popitem(last=False)         # Remove first item (useful for LRU cache)

Sorting & Searching

sorted([3,1,2])                          # [1, 2, 3]  — returns new list
sorted([3,1,2], reverse=True)            # [3, 2, 1]
sorted(["banana","apple"], key=len)      # ['apple', 'banana']
sorted(pairs, key=lambda x: (x[1], -x[0]))  # Multi-key sort

arr.sort()                               # In-place sort (returns None)
arr.sort(key=lambda x: x[1])

# Binary search (requires sorted list)
import bisect
bisect.bisect_left([1,3,5,7], 5)    # 2  — leftmost position to insert 5
bisect.bisect_right([1,3,5,7], 5)   # 3  — rightmost position to insert 5
bisect.insort(arr, val)              # Insert val keeping arr sorted

Heap (Min-Heap by default)

import heapq

heap = []
heapq.heappush(heap, 3)            # Push → [3]
heapq.heappush(heap, 1)            # Push → [1, 3]
heapq.heappop(heap)                # Pop smallest → 1
heapq.heappushpop(heap, 5)         # Push then pop → more efficient
heapq.nlargest(2, [1,5,3,7])      # [7, 5]  — top 2 largest
heapq.nsmallest(2, [1,5,3,7])     # [1, 3]  — top 2 smallest

# Max-heap trick: negate values
heapq.heappush(heap, -val)
max_val = -heapq.heappop(heap)

# Heapify existing list
arr = [5, 3, 1, 4]
heapq.heapify(arr)                 # In-place → [1, 3, 5, 4]

Itertools

from itertools import permutations, combinations, product, accumulate, groupby, chain

list(permutations([1,2,3]))           # All orderings: (1,2,3),(1,3,2),...  — 6 total
list(permutations([1,2,3], 2))        # 2-length perms: (1,2),(1,3),(2,1),...

list(combinations([1,2,3], 2))        # Choose 2: (1,2),(1,3),(2,3)
list(combinations_with_replacement([1,2], 2))  # (1,1),(1,2),(2,2)

list(product([1,2], [3,4]))           # Cartesian product: (1,3),(1,4),(2,3),(2,4)
list(product([0,1], repeat=3))        # All 3-bit combos: (0,0,0)...(1,1,1)

list(accumulate([1,2,3,4]))           # Prefix sums: [1, 3, 6, 10]
list(accumulate([1,2,3], max))        # Running max: [1, 2, 3]

list(chain([1,2], [3,4]))             # Flatten: [1, 2, 3, 4]

Built-in Functions

zip(a, b)                    # Pair elements → zip([1,2],[3,4]) → [(1,3),(2,4)]
zip(*matrix)                 # Transpose matrix
enumerate(arr)               # Index + value → [(0,'a'),(1,'b')]
enumerate(arr, start=1)      # Start from 1

map(int, ["1","2","3"])      # Apply func → [1, 2, 3]  (returns iterator)
map(str, [1, 2, 3])          # → ['1', '2', '3']
filter(lambda x: x > 0, [-1,2,-3,4])  # → [2, 4]

min(arr)                     # Minimum value
min(arr, key=len)            # Min by custom key
max(arr, key=lambda x: x[1]) # Max by second element
sum(arr)                     # Sum all elements
sum(arr, start=10)           # Sum with initial value

all([True, True, False])     # True if ALL true → False
any([False, False, True])    # True if ANY true → True
abs(-5)                      # Absolute value → 5
divmod(17, 5)                # (quotient, remainder) → (3, 2)
pow(2, 10)                   # 2^10 → 1024
pow(2, 10, 1000)             # 2^10 % 1000 → 24  (modular exponentiation)

Sets

s = {1, 2, 3}
s.add(4)                # {1, 2, 3, 4}
s.remove(2)             # Remove (raises KeyError if missing)
s.discard(99)           # Remove (no error if missing)
s.pop()                 # Remove and return arbitrary element

a = {1, 2, 3}
b = {2, 3, 4}
a & b                   # Intersection → {2, 3}
a | b                   # Union → {1, 2, 3, 4}
a - b                   # Difference → {1}
a ^ b                   # Symmetric difference → {1, 4}
a.issubset(b)           # Is a ⊆ b? → False
a.issuperset(b)         # Is a ⊇ b? → False

Common Patterns

Two Pointers

# Sorted two-sum
def twoSum(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        s = arr[left] + arr[right]
        if s == target: return [left, right]
        elif s < target: left += 1
        else: right -= 1
    return []

Sliding Window

# Max sum of subarray of size k
def maxSumWindow(arr, k):
    window = sum(arr[:k])
    best = window
    for i in range(k, len(arr)):
        window += arr[i] - arr[i - k]
        best = max(best, window)
    return best

Prefix Sum

# Subarray sum equals k (count)
from collections import defaultdict
def subarraySum(nums, k):
    prefix = defaultdict(int)
    prefix[0] = 1
    total = count = 0
    for x in nums:
        total += x
        count += prefix[total - k]
        prefix[total] += 1
    return count

Binary Search on Answer

# Koko eating bananas — min speed to eat all piles in h hours
import math
def minEatingSpeed(piles, h):
    lo, hi = 1, max(piles)
    while lo < hi:
        mid = (lo + hi) // 2
        if sum(math.ceil(p / mid) for p in piles) <= h:
            hi = mid
        else:
            lo = mid + 1
    return lo

Top-K with Heap

import heapq
def topKFrequent(nums, k):
    freq = Counter(nums)
    return heapq.nlargest(k, freq.keys(), key=freq.get)

Quick Reference Table

Need Use
Count frequencies Counter(iterable)
Group by key defaultdict(list)
BFS queue deque() with popleft()
LRU cache OrderedDict with move_to_end / popitem
Top-K elements heapq.nlargest(k, ...)
Sorted insert bisect.insort(arr, val)
All permutations itertools.permutations(arr)
All combinations itertools.combinations(arr, k)
Prefix sums itertools.accumulate(arr)
Transpose matrix list(zip(*matrix))
Flatten 2D list [x for row in matrix for x in row]
Reverse anything s[::-1] or arr[::-1]